package com.ruoyi.safe.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.core.domain.entity.CommonCheckType;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.quality.domain.dto.TQualityBizEnterCheckDTO;
import com.ruoyi.safe.domain.BizEnterCheck;
import com.ruoyi.safe.domain.BizEnterCheckProject;
import com.ruoyi.safe.domain.BizEnterTask;
import com.ruoyi.safe.domain.BizProjectCheckRecord;
import com.ruoyi.safe.domain.CommonProject;
import com.ruoyi.safe.domain.dto.BizEnterCheckDTO;
import com.ruoyi.safe.domain.dto.BizEnterDTO;
import com.ruoyi.safe.domain.dto.EnterCheckDTO;
import com.ruoyi.safe.domain.dto.StatisticsDto;
import com.ruoyi.safe.domain.vo.BizEnterDataPivotHiddenTypeStatisticsVO;
import com.ruoyi.safe.domain.vo.BizEnterDataPivotProjectStatisticsVO;
import com.ruoyi.safe.domain.vo.BizEnterDataPivotVO;
import com.ruoyi.safe.mapper.BizEnterCheckMapper;
import com.ruoyi.safe.mapper.BizEnterCheckProjectMapper;
import com.ruoyi.safe.mapper.BizEnterTaskMapper;
import com.ruoyi.safe.mapper.BizProjectCheckMapper;
import com.ruoyi.safe.mapper.BizProjectCheckRecordMapper;
import com.ruoyi.safe.mapper.CommonCheckTypeMapper;
import com.ruoyi.safe.mapper.CommonProjectMapper;
import com.ruoyi.safe.service.IBizEnterCheckService;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 公司检查Service业务层处理
 *
 * @author ruoyi
 * @date 2023-12-05
 */
@Slf4j
@Service
public class BizEnterCheckServiceImpl implements IBizEnterCheckService {
    private static final String  NORMAL_HIDDEN = "1";

    private static final String  MAJOR_HIDDEN = "2";

    @Autowired
    private BizEnterCheckMapper bizEnterCheckMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private CommonCheckTypeMapper commonCheckTypeMapper;
    @Autowired
    private BizEnterCheckProjectMapper bizEnterCheckProjectMapper;
    @Autowired
    private BizEnterTaskMapper bizEnterTaskMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private BizProjectCheckMapper bizProjectCheckMapper;
    @Autowired
    private BizProjectCheckRecordMapper bizProjectCheckRecordMapper;
    @Autowired
    private CommonProjectMapper commonProjectMapper;

    /**
     * 查询公司检查
     *
     * @param id 公司检查主键
     * @return 公司检查
     */
    @Override
    public BizEnterCheck selectBizEnterCheckById(Long id) {
        return bizEnterCheckMapper.selectBizEnterCheckById(id);
    }

    /**
     * 查询公司检查列表
     *
     * @param bizEnterCheckDTO 公司检查
     * @return 公司检查
     */
    @Override
    public List<BizEnterCheck> selectBizEnterCheckList(BizEnterCheckDTO bizEnterCheckDTO, SysUser user) {
        BizEnterCheck bizEnterCheck = new BizEnterCheck();
        BeanUtils.copyProperties(bizEnterCheckDTO, bizEnterCheck);
        if(StringUtils.isNotNull(bizEnterCheck.getDate())){
            bizEnterCheck.setStartTime(bizEnterCheck.getDate()[0]);
            bizEnterCheck.setEndTime(bizEnterCheck.getDate()[1]);
        }
        //根据用户信息查询本用户所属企业及下级部门的信息
        List<SysDept> sysDepts = sysDeptMapper.selectChildrenDeptById(user.getDeptId());
        StringBuilder sb = new StringBuilder(String.valueOf(user.getDeptId()));
        for (SysDept dept : sysDepts) {
            sb.append(',').append(dept.getDeptId());
        }
        bizEnterCheck.setDeptIds(sb.toString());
        if (bizEnterCheckDTO.getPageNum() != null && bizEnterCheckDTO.getPageSize() != null) {
            PageUtils.startPage(bizEnterCheckDTO.getPageNum(), bizEnterCheckDTO.getPageSize());
        }
        PageUtils.orderBy("create_time desc");
        List<BizEnterCheck> bizEnterCheckList = bizEnterCheckMapper.selectBizEnterCheckList(bizEnterCheck);
        PageUtils.clearPage();
        //组织名称为A/AA
        handleEnterCheck(bizEnterCheckList);

        return bizEnterCheckList;
    }

    private void handleEnterCheck(List<BizEnterCheck> bizEnterCheckList) {
        bizEnterCheckList.stream().forEach(item -> {
            SysUser sysUser = sysUserMapper.selectUserByUserName(item.getCreateBy());
            SysDept sysDept = sysDeptMapper.selectDeptById(sysUser.getDeptId());
            String[] ancestors = sysDept.getAncestors().split(",");
            List<String> list = Arrays.asList(ancestors);
            List arrayList = new ArrayList();
            list.stream().filter(a -> Long.valueOf(a) != 0).forEach(a -> {
                arrayList.add(sysDeptMapper.selectDeptById(Long.valueOf(a)).getDeptName());
            });
            if (sysDept.getAncestors().length() == 1) {
                item.setDeptName(sysDept.getDeptName());
            } else {
                item.setDeptName(StringUtils.join(arrayList, "/") + "/" + sysDept.getDeptName());
            }

            //拼接检查类型
            CommonCheckType commonCheckType = commonCheckTypeMapper.selectCommonCheckTypeById(item.getCheckType());
            List<String> checkNameList = new ArrayList<>();
            Arrays.asList(commonCheckType.getAncestors().split(",")).forEach(ancestor -> {//[5,502]
                String checkTypeName = commonCheckTypeMapper.selectListTypeByTypeNo(Long.valueOf(ancestor)).getCheckTypeName();
                checkNameList.add(checkTypeName);
            });
            item.setCheckTypeName(StringUtils.join(checkNameList,"/"));
            //检查进度  该检查下的 已完成数量/项目数
            List<BizEnterTask> bizEnterTasks = bizEnterTaskMapper.selectBizEnterTaskList(null);
            if(bizEnterTasks != null){
                long count1 = bizEnterTasks.stream().filter(a -> (a.getBizEnterCheckId()).equals(item.getId())).count();
                long count2 = bizEnterTasks.stream().filter(a -> (a.getBizEnterCheckId()).equals(item.getId()) && ("3").equals(a.getStatus())).count();
                item.setCheckLoading(count2 + "/" +count1);
                //项目隐患整改率 该检查下的 完成的整改个数/隐患总数
                if(count2 > 0){
                    BigDecimal decimal = new BigDecimal(count2).divide(new BigDecimal(count1), 2, RoundingMode.HALF_UP)
                            .multiply(new BigDecimal(100));;
                    item.setHiddenDate(decimal);
                }else{
                    item.setHiddenDate(new BigDecimal(0));
                }
            }

            item.setCreateBy(sysUser.getNickName());
        });
    }

    /**
     * 我参与的检查
     *
     * @param bizEnterCheck
     * @return
     */
    @Override
    public List<BizEnterCheck> selectBizEnterMyList(BizEnterCheck bizEnterCheck, SysUser user) {
        bizEnterCheck.setCreateBy(user.getUserName());
        PageUtils.orderBy("create_time desc");
        List<BizEnterCheck> bizEnterCheckList = bizEnterCheckMapper.selectBizEnterCheckList(bizEnterCheck);
        handleEnterCheck(bizEnterCheckList);
        return bizEnterCheckList;
    }


    /**
     * 点发送任务按钮，新增到企业检查表和企业检查-项目表中
     *
     * @param bizEnterDTO
     * @return
     */
    @Override
    @Transactional
    public int insertEnter(BizEnterDTO bizEnterDTO, SysUser user) {
        //企业检查
        //生成公司检查id
        bizEnterDTO.getBizEnterCheck().setId(IdUtil.getSnowflakeNextId());
        bizEnterDTO.getBizEnterCheck().setCreateTime(DateUtils.getNowDate());
        bizEnterDTO.getBizEnterCheck().setDeptName(user.getDeptId().toString());
        bizEnterDTO.getBizEnterCheck().setCreateBy(user.getUserName());
        //任务已下发
        bizEnterDTO.getBizEnterCheck().setCheckStatus("1");
        bizEnterCheckMapper.insertBizEnterCheck(bizEnterDTO.getBizEnterCheck());

        //企业检查-项目
        bizEnterDTO.getBizEnterCheckProject().forEach(item -> {
            //企业检查--任务
            Arrays.stream(item.getCheckProjectIds().split(",")).forEach(projectId -> {
                BizEnterCheckProject bizEnterCheckProject = new BizEnterCheckProject();
                BeanUtil.copyProperties(item, bizEnterCheckProject);
                bizEnterCheckProject.setId(IdUtil.getSnowflakeNextId());
                bizEnterCheckProject.setBizEnterCheckId(bizEnterDTO.getBizEnterCheck().getId());
                bizEnterCheckProject.setCreateBy(user.getUserName());
                bizEnterCheckProject.setCreateTime(DateUtils.getNowDate());
                bizEnterCheckProject.setCheckProjectIds(projectId);
                bizEnterCheckProjectMapper.insertBizEnterCheckProject(bizEnterCheckProject);

                BizEnterTask task = new BizEnterTask();
                task.setId(IdUtil.getSnowflakeNextId());
                task.setBizEnterCheckId(bizEnterDTO.getBizEnterCheck().getId());
                task.setBizEnterCheckProjectId(bizEnterCheckProject.getId());
                task.setProjectId(Long.valueOf(projectId));
                task.setStatus(bizEnterDTO.getBizEnterCheck().getCheckStatus());
                task.setCreateBy(user.getUserName());
                task.setCreateTime(DateUtils.getNowDate());
                bizEnterTaskMapper.insertBizEnterTask(task);
            });
        });

        return 1;
    }


    /**
     * 我的待办
     * @param bizEnterCheckDTO
     * @return
     */
    @Override
    public List<EnterCheckDTO> selectToDoList(BizEnterCheckDTO bizEnterCheckDTO, SysUser user) {
        if (bizEnterCheckDTO.getPageNum() != null && bizEnterCheckDTO.getPageSize() != null) {
            PageUtils.startPage(bizEnterCheckDTO.getPageNum(), bizEnterCheckDTO.getPageSize());
        }
        PageUtils.orderBy("create_time desc");
        if (bizEnterCheckDTO.getSelectType() == null || !bizEnterCheckDTO.getSelectType().equals("1"))
        {
            bizEnterCheckDTO.setSelectType("0");
        }
        bizEnterCheckDTO.setUserName(user.getUserName());
        bizEnterCheckDTO.setUserId(String.valueOf(user.getUserId()));
        List<EnterCheckDTO> enterCheckDTOList = bizEnterTaskMapper.selectToDoList(bizEnterCheckDTO);
//        PageUtils.clearPage();
//        List<EnterCheckDTO> collect = enterCheckDTOList.stream()
//                .filter(a -> a.getCreateBy().equals(user.getUserName()))
//                .collect(Collectors.toList());
        //组织名称为A/AA
        enterCheckDTOList.stream().forEach(item -> {
            SysUser sysUser = sysUserMapper.selectUserByUserName(item.getCreateBy());
            SysDept sysDept = sysDeptMapper.selectDeptById(sysUser.getDeptId());
            String[] ancestors = sysDept.getAncestors().split(",");
            List<String> list = Arrays.asList(ancestors);
            List arrayList = new ArrayList();
            list.stream().filter(a -> Long.valueOf(a) != 0).forEach(a -> {
                arrayList.add(sysDeptMapper.selectDeptById(Long.valueOf(a)).getDeptName());
            });
            if (sysDept.getAncestors().length() == 1) {
                item.setDeptName(sysDept.getDeptName());
            } else {
                item.setDeptName(StringUtils.join(arrayList, "/") + "/" + sysDept.getDeptName());
            }
            //拼接检查类型
            List<CommonCheckType> commonCheckTypeList = commonCheckTypeMapper.selectCommonCheckTypeList(null);
            commonCheckTypeList.stream().forEach(c -> {
                String[] split = c.getAncestors().split(",");
                List<String> CommonAncestorsList = Arrays.asList(split);
                List commonList = new ArrayList();
                CommonAncestorsList.stream().forEach(b -> {
                    String checkTypeName = commonCheckTypeMapper.selectListTypeByTypeNo(Long.valueOf(b)).getCheckTypeName();
                    commonList.add(checkTypeName);
                });
                item.setCheckType(StringUtils.join(commonList, "/"));
            });
            item.setCreateBy(user.getNickName());
        });
        return enterCheckDTOList;
    }

    /**
     * 新增公司检查
     *
     * @param bizEnterCheck 公司检查
     * @return 结果
     */
    @Override
    public int insertBizEnterCheck(BizEnterCheck bizEnterCheck, SysUser user) {
        //生成Id
        bizEnterCheck.setId(IdUtil.getSnowflakeNextId());
        bizEnterCheck.setCreateTime(DateUtils.getNowDate());
        bizEnterCheck.setCreateBy(user.getUserName());
        //任务已下发
        bizEnterCheck.setCheckStatus("1");
        return bizEnterCheckMapper.insertBizEnterCheck(bizEnterCheck);
    }

    /**
     * 修改公司检查
     *
     * @param bizEnterCheck 公司检查
     * @return 结果
     */
    @Override
    public int updateBizEnterCheck(BizEnterCheck bizEnterCheck, SysUser user) {
        bizEnterCheck.setUpdateTime(DateUtils.getNowDate());
        bizEnterCheck.setUpdateBy(user.getUserName());
        return bizEnterCheckMapper.updateBizEnterCheck(bizEnterCheck);
    }

    /**
     * 批量删除公司检查
     *
     * @param ids 需要删除的公司检查主键
     * @return 结果
     */
    @Override
    public int deleteBizEnterCheckByIds(Long[] ids) {
        //删除公司检查的同时同步删除项目，任务中的数据
        for (Long id :ids){
            //删除项目表中公司检查为id的
            List<BizEnterCheckProject> bizEnterCheckProjectList = bizEnterCheckProjectMapper.selectProjectListByCheckId(id);
            bizEnterCheckProjectList.stream().forEach(a ->{
                bizEnterCheckProjectMapper.deleteListByCheckId(a.getBizEnterCheckId());
            });
            //删除任务表中公司检查为id的
            List<BizEnterTask> bizEnterTaskList = bizEnterTaskMapper.selectTaskListByCheckId(id);
            bizEnterTaskList.stream().forEach(b -> {
                bizEnterTaskMapper.deleteListByCheckId(b.getBizEnterCheckId());
            });
        }
        return bizEnterCheckMapper.deleteBizEnterCheckByIds(ids);
    }

    /**
     * 删除公司检查信息
     *
     * @param id 公司检查主键
     * @return 结果
     */
    @Override
    public int deleteBizEnterCheckById(Long id) {
        return bizEnterCheckMapper.deleteBizEnterCheckById(id);
    }

    /**
     * 查询公司检查数据透视
     *
     * @param id 公司检查主键
     * @return 公司检查
     */
    @Override
    public BizEnterDataPivotVO getDataPivotById(Long id) {
        List<BizEnterCheckProject> bizEnterCheckProjects = bizEnterCheckProjectMapper.selectProjectListByCheckId(id);
        if (!CollectionUtils.isEmpty(bizEnterCheckProjects)) {
            Long[] ids = bizEnterCheckProjects.stream().map(BizEnterCheckProject::getId).toArray(Long[]::new);
            List<BizProjectCheckRecord> bizProjectCheckRecords = bizProjectCheckRecordMapper
                    .selectListByProjectCheckIds(ids);
            Map<Long, Long> projectMap = bizProjectCheckRecords.stream()
                    .collect(Collectors.groupingBy(BizProjectCheckRecord::getProjectId, Collectors.counting()));
            List<BizEnterDataPivotProjectStatisticsVO> projectStatistics = new ArrayList<>();
            projectMap.forEach((k, v) -> {
                BizEnterDataPivotProjectStatisticsVO projectStatisticsVO = new BizEnterDataPivotProjectStatisticsVO();
                CommonProject project = commonProjectMapper.selectCommonProjectById(k);
                projectStatisticsVO.setProjectName(project.getName());
                projectStatisticsVO.setHiddenNum(v.intValue());
                projectStatistics.add(projectStatisticsVO);
            });

            List<BizEnterDataPivotHiddenTypeStatisticsVO> hiddenTypeStatisticsVOList = new ArrayList<>();
            Map<String, Long> hiddenTypeMap = bizProjectCheckRecords.stream()
                    .collect(Collectors.groupingBy(BizProjectCheckRecord::getHiddenClass, Collectors.counting()));
            hiddenTypeMap.forEach((k, v) -> {
                BizEnterDataPivotHiddenTypeStatisticsVO hiddenTypeStatisticsVO = new BizEnterDataPivotHiddenTypeStatisticsVO();
                hiddenTypeStatisticsVO.setHiddenType(k);
                hiddenTypeStatisticsVO.setNum(v.intValue());
                hiddenTypeStatisticsVOList.add(hiddenTypeStatisticsVO);
            });

            BizEnterDataPivotVO dataPivotVO = new BizEnterDataPivotVO();

            BizEnterCheck bizEnterCheck = bizEnterCheckMapper.selectBizEnterCheckById(id);
            dataPivotVO.setCheckName(bizEnterCheck.getCheckName());
            dataPivotVO.setCheckProjectNum((long) projectMap.size());
            dataPivotVO.setHiddenNum((long) bizProjectCheckRecords.size());
            dataPivotVO.setNormalHiddenNum(bizProjectCheckRecords.stream().filter(r -> NORMAL_HIDDEN.equals(r.getAccidentHidden()))
                    .count());
            dataPivotVO.setMajorHiddenNum(bizProjectCheckRecords.stream().filter(r -> MAJOR_HIDDEN.equals(r.getAccidentHidden()))
                    .count());
            dataPivotVO.setProjectStatistics(projectStatistics);
            dataPivotVO.setHiddenTypeStatistics(hiddenTypeStatisticsVOList);

            return dataPivotVO;
        }
        return new BizEnterDataPivotVO();
    }

    @Override
    public Long countByStatisticsDto(StatisticsDto statisticsDto, SysUser user) {

        List<SysDept> sysDepts = sysDeptMapper.selectChildrenDeptById(user.getDeptId());
        StringBuilder sb = new StringBuilder(String.valueOf(user.getDeptId()));
        for (SysDept dept : sysDepts) {
            sb.append(',').append(dept.getDeptId());
        }
        Long count = bizEnterCheckMapper.countByStatisticsDto(statisticsDto, sb.toString());
        return count;
    }
}
